<!-- src/views/admin/HeritageList.vue -->
<template>
  <div class="admin-content-page">
    <div class="page-header">
      <h1>文化遗产管理</h1>
      <div class="header-actions">
        <el-select
            v-model="searchCategoryId"
            placeholder="请选择分类"
            clearable
            class="search-select"
            @change="handleSearch"
        >
          <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
        <el-input
            v-model="searchName"
            placeholder="请输入遗产名称进行搜索"
            prefix-icon="Search"
            class="search-input"
            @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;">
          搜索
        </el-button>
        <el-button @click="handleReset" style="margin-left: 10px;">
          重置
        </el-button>
        <el-button type="primary" @click="showAddDialog">新增遗产</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="heritageList" style="width: 100%">
      <el-table-column label="ID" width="80">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="遗产名称" width="200"></el-table-column>
      <el-table-column prop="categoryId" label="所属分类" width="150">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="coverImage" label="封面图片" width="120">
        <template #default="scope">
          <el-image
              v-if="scope.row.coverImage"
              :src="scope.row.coverImage"
              :preview-src-list="[scope.row.coverImage]"
              class="heritage-image"
              fit="cover"
              lazy
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="遗产简介" width="300"></el-table-column>
      <el-table-column prop="viewCount" label="浏览量" width="100"></el-table-column>
      <el-table-column prop="likeCount" label="点赞数" width="100"></el-table-column>
      <el-table-column prop="collectCount" label="收藏数" width="100"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" :formatter="formatDate"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="200" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="showEditDialog(scope.row)" style="margin-right: 10px;">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDeleteHeritage(scope.row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        class="pagination-container"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 新增遗产对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增文化遗产" width="600px" destroy-on-close>
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="addForm.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="遗产名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入遗产名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="遗产简介" prop="description">
          <el-input v-model="addForm.description" type="textarea" placeholder="请输入遗产简介" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="详细内容" prop="detailContent">
          <el-input
              v-model="addForm.detailContent"
              type="textarea"
              placeholder="请输入遗产详细内容"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="封面图片">
          <div class="image-upload-section">
            <el-avatar
                :size="80"
                class="heritage-avatar"
                @click="handleAddAvatarClick"
            >
              <img v-if="addForm.coverImage" :src="addForm.coverImage" alt="封面图片" />
              <el-icon v-else><Plus /></el-icon>
            </el-avatar>
            <input
                ref="addAvatarInput"
                type="file"
                accept="image/*"
                style="display: none"
                @change="handleAddAvatarUpload"
            />
            <div class="avatar-tip">点击上传图片</div>
            <el-button
                v-if="addForm.coverImage"
                type="danger"
                size="small"
                @click="removeAddAvatar"
                style="margin-top: 10px"
            >
              移除图片
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddHeritage" :loading="loading">
            <el-icon v-if="loading"><Loading /></el-icon>
            <span>保存</span>
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑遗产对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑文化遗产" width="600px" destroy-on-close>
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="遗产名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入遗产名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="遗产简介" prop="description">
          <el-input v-model="editForm.description" type="textarea" placeholder="请输入遗产简介" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="详细内容" prop="detailContent">
          <el-input
              v-model="editForm.detailContent"
              type="textarea"
              placeholder="请输入遗产详细内容"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="封面图片">
          <div class="image-upload-section">
            <el-avatar
                :size="80"
                class="heritage-avatar"
                @click="handleEditAvatarClick"
            >
              <img v-if="editForm.coverImage" :src="editForm.coverImage" alt="封面图片" />
              <el-icon v-else><Plus /></el-icon>
            </el-avatar>
            <input
                ref="editAvatarInput"
                type="file"
                accept="image/*"
                style="display: none"
                @change="handleEditAvatarUpload"
            />
            <div class="avatar-tip">点击上传图片</div>
            <el-button
                v-if="editForm.coverImage"
                type="danger"
                size="small"
                @click="removeEditAvatar"
                style="margin-top: 10px"
            >
              移除图片
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateHeritage" :loading="loading">
            <el-icon v-if="loading"><Loading /></el-icon>
            <span>保存</span>
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Search, Loading, Plus } from '@element-plus/icons-vue'
import {
  findHeritagePage,
  addHeritage,
  updateHeritage,
  deleteHeritage,
  uploadHeritageImage // 使用正确的函数名
} from '@/api/heritage.js'
import { findCategoryPage } from '@/api/category.js'

// 响应式数据
const heritageList = ref([])
const categoryList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchName = ref('')
const searchCategoryId = ref('')

// 新增遗产相关数据
const addDialogVisible = ref(false)
const addForm = ref({
  categoryId: '',
  name: '',
  coverImage: '',
  description: '',
  detailContent: ''
})
const addFormRules = ref({
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入遗产名称', trigger: 'blur' },
    { max: 50, message: '遗产名称不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '遗产简介不能超过200个字符', trigger: 'blur' }
  ]
})
const addFormRef = ref(null)
const addAvatarInput = ref(null)

// 编辑遗产相关数据
const editDialogVisible = ref(false)
const editForm = ref({
  id: '',
  categoryId: '',
  name: '',
  coverImage: '',
  description: '',
  detailContent: ''
})
const editFormRules = ref({
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入遗产名称', trigger: 'blur' },
    { max: 50, message: '遗产名称不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '遗产简介不能超过200个字符', trigger: 'blur' }
  ]
})
const editFormRef = ref(null)
const editAvatarInput = ref(null)

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await findCategoryPage({ current: 1, size: 1000 })
    if (response.success && response.data && response.data.records) {
      categoryList.value = response.data.records
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '未知分类'
}

// 图片上传相关方法
const handleAddAvatarClick = () => {
  addAvatarInput.value.click()
}

const handleEditAvatarClick = () => {
  editAvatarInput.value.click()
}

const handleAddAvatarUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型和大小
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return
  }

  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB')
    return
  }

  try {
    loading.value = true
    // 调用后端上传接口
    const response = await uploadHeritageImage(file)

    if (response.success || response.errorCode === 20000) {
      addForm.value.coverImage = response.data || response
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(response.message || '图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败，请稍后重试')
    console.error('图片上传出错:', error)
  } finally {
    loading.value = false
    // 清空文件输入，允许重复选择同一文件
    event.target.value = ''
  }
}

const handleEditAvatarUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型和大小
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return
  }

  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB')
    return
  }

  try {
    loading.value = true
    // 调用后端上传接口
    const response = await uploadHeritageImage(file)

    if (response.success || response.errorCode === 20000) {
      editForm.value.coverImage = response.data || response
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(response.message || '图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败，请稍后重试')
    console.error('图片上传出错:', error)
  } finally {
    loading.value = false
    // 清空文件输入，允许重复选择同一文件
    event.target.value = ''
  }
}

const removeAddAvatar = () => {
  addForm.value.coverImage = ''
  ElMessage.info('已移除图片')
}

const removeEditAvatar = () => {
  editForm.value.coverImage = ''
  ElMessage.info('已移除图片')
}

// 获取遗产列表
const fetchHeritageList = async (showLoading = true) => {
  if (showLoading) {
    loading.value = true
  }
  try {
    const pageDTO = {
      current: currentPage.value,
      size: pageSize.value,
      name: searchName.value || undefined,
      categoryId: searchCategoryId.value || undefined
    }

    const response = await findHeritagePage(pageDTO)

    if (response.success) {
      if (response.data && response.data.records) {
        heritageList.value = response.data.records
        total.value = response.data.total || 0
      } else {
        heritageList.value = []
        total.value = 0
      }
    } else {
      ElMessage.error(response.message || '获取遗产列表失败')
      heritageList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取遗产列表失败:', error)
    ElMessage.error('获取遗产列表失败')
    heritageList.value = []
    total.value = 0
  } finally {
    if (showLoading) {
      loading.value = false
    }
  }
}


// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchHeritageList()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchHeritageList()
}

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) {
    return '--'
  }
  const date = new Date(cellValue)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 显示新增对话框
const showAddDialog = () => {
  addForm.value = {
    categoryId: '',
    name: '',
    coverImage: '',
    description: '',
    detailContent: ''
  }
  addDialogVisible.value = true
}

// 新增遗产
const handleAddHeritage = async () => {
  try {
    await addFormRef.value.validate()

    loading.value = true
    const response = await addHeritage(addForm.value)

    if (response.success) {
      ElMessage.success('新增遗产成功')
      addDialogVisible.value = false
      fetchHeritageList()
    } else {
      ElMessage.error(response.message || '新增遗产失败')
    }
  } catch (error) {
    console.error('新增遗产失败:', error)
    ElMessage.error('新增遗产失败')
  } finally {
    loading.value = false
  }
}

// 显示编辑对话框
const showEditDialog = (heritage) => {
  editForm.value = {
    id: heritage.id,
    categoryId: heritage.categoryId,
    name: heritage.name,
    coverImage: heritage.coverImage || '',
    description: heritage.description || '',
    detailContent: heritage.detailContent || ''
  }
  editDialogVisible.value = true
}

// 更新遗产
const handleUpdateHeritage = async () => {
  try {
    await editFormRef.value.validate()

    loading.value = true
    const response = await updateHeritage(editForm.value)

    if (response.success) {
      ElMessage.success('更新遗产成功')
      editDialogVisible.value = false
      fetchHeritageList()
    } else {
      ElMessage.error(response.message || '更新遗产失败')
    }
  } catch (error) {
    console.error('更新遗产失败:', error)
    ElMessage.error('更新遗产失败')
  } finally {
    loading.value = false
  }
}

// 删除遗产
const handleDeleteHeritage = async (heritage) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除遗产"${heritage.name}"吗？删除后将无法恢复`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    loading.value = true
    const response = await deleteHeritage(heritage.id)

    if (response.success) {
      ElMessage.success('删除遗产成功')
      fetchHeritageList()
    } else {
      ElMessage.error(response.message || '删除遗产失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除遗产失败:', error)
      ElMessage.error('删除遗产失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
  fetchHeritageList()
}

// 重置搜索条件
const handleReset = () => {
  searchName.value = ''
  searchCategoryId.value = ''
  currentPage.value = 1
  fetchHeritageList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategoryList()
  fetchHeritageList()
})
</script>

<style scoped>
.admin-content-page {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.search-select {
  width: 150px;
}

.pagination-container {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.heritage-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
}

.image-upload-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.heritage-avatar {
  border: 2px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;
}

.heritage-avatar:hover {
  border-color: #409eff;
  transform: scale(1.05);
}

.avatar-tip {
  text-align: center;
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}
</style>
